package com.example.kerberostest;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hive.jdbc.HiveConnection;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.security.PrivilegedAction;
import java.sql.*;
import java.util.ArrayList;

public class HiveClient extends JFrame {
    private static final String DRIVER_NAME = "org.apache.hive.jdbc.HiveDriver";
    private static final String CONNECTION_URL = "jdbc:hive2://slave2.tobehacker.com:10000/;principal=hive/slave2.tobehacker.com@TOBEHACKER.COM;auth=kerberos";

    private JPanel mainPanel;
    private JLabel messageLabel;
    private JTextArea sqlTextArea;
    private JButton executeButton;
    private JTable resultTable;

    public HiveClient() {
        super("Hive Client");
        initComponents();
    }

    private void initComponents() {
        mainPanel = new JPanel(new BorderLayout(10, 10));
        messageLabel = new JLabel("Please enter your Hive SQL below:");
        sqlTextArea = new JTextArea(10, 50);
        executeButton = new JButton("Execute");
        resultTable = new JTable();

        // 给执行按钮添加点击事件
        executeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ResultSetTableModel tableModel = executeSQL();
                if (tableModel != null) {
                    resultTable.setModel(tableModel);
                }
            }
        });

        // 把组件添加到面板上
        mainPanel.add(messageLabel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(sqlTextArea), BorderLayout.CENTER);
        mainPanel.add(executeButton, BorderLayout.EAST);
        mainPanel.add(new JScrollPane(resultTable), BorderLayout.SOUTH);

        // 设置窗口属性
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setContentPane(mainPanel);
        this.pack();
        this.setVisible(true);
    }

    private ResultSetTableModel executeSQL() {
        String sql = sqlTextArea.getText().trim();

        if (sql.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter a Hive SQL statement.", "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }
        try {
            // 加载Hive JDBC驱动
            Class.forName(DRIVER_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Failed to load Hive JDBC driver.", "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }
        // 设置Kerberos环境
        System.setProperty("java.security.krb5.conf", "src/main/resources/krb5.conf");
        Configuration configuration = new Configuration();
        configuration.set("hadoop.security.authentication", "Kerberos");
        UserGroupInformation.setConfiguration(configuration);

        // 获取Kerberos认证信息
        UserGroupInformation UGI;
        try {
            UGI = UserGroupInformation.loginUserFromKeytabAndReturnUGI("tust@TOBEHACKER.COM", "src/main/resources/tust.keytab");
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Failed to get Kerberos authentication information.", "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }

        // 执行Hive SQL
        final ResultSetTableModel[] model = {null};


        UGI.doAs((PrivilegedAction<Void>) () -> {
            try {
                // 获取Hive JDBC连接
                Connection connection = DriverManager.getConnection(CONNECTION_URL);
                // 执行Hive SQL
                ResultSet resultSet = connection.createStatement().executeQuery(sql);
                // 判断是否有结果集
//                if (resultSet != null) {
//                     model[0] = new ResultSetTableModel(resultSet);
//                    SwingUtilities.invokeLater(() -> resultTable.setModel(model[0]));
//                }
                if (resultSet.next()) {
                    model[0] = new ResultSetTableModel(resultSet);
                    SwingUtilities.invokeLater(() -> resultTable.setModel(model[0]));
                } else {
                    SwingUtilities.invokeLater(() -> resultTable.setModel(new DefaultTableModel()));
                }

                // 关闭ResultSet和Connection对象
                resultSet.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(HiveClient.this, "Failed to execute Hive SQL: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
            return null;
        });
        return model[0];
    }




    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new HiveClient();
            }
        });
    }
}
